<?php
require_once( '../system/smarty.inc' );
require_once( '../system/mdao/Class_M_COST_DM_TYPE.php' );
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );

Class_PWD::valid_auth(AOKI_AUTH_COST_DM,$login['staff_auth']);
$smarty->assign('now_menu', $aokimenu[AOKI_AUTH_COST_DM]["li"]);
$login_auth = $login['staff_auth'];
$smarty->assign('login_auth',$login_auth);

$dao = new Class_M_COST_DM_TYPE;
$types = Class_M_OTHER::get_dmtype_array();
if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	if( isset($_GET['id']) && $_GET['id'] != '' ){
		$forms  = $dao->get( $_GET['id'] );
		$forms["id"] = $_GET['id'];
	}
}else{
	$forms = $_POST;
	if( $forms['mode'] == 'input' ){
		$err   = new Class_ERROR;
		$chk   = $dao->get_checks();
		
		foreach ($chk as $kcol => $chkval) {
			$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
		}
		
		if ( $err->clear ){
			$cols     = $dao->get_cols();
			foreach($cols as $kcol => $val) {
				$values[$kcol] = $forms[$kcol] ;
			}
			
			//桁数チェック
			$maxlens = $dao->get_maxlens();
			foreach ( $maxlens as $k => $v ) {
				$err_mes[$k] =$err->check_size($values[$k], $v);
			}
		}
		
		if ( $err->clear ){
			if( $forms['id'] == '' ){
				$where = sprintf(" type_name = '%s' " , $forms['type_name'] );
			}else{
				$where = sprintf(" type_name = '%s' AND id  <> %s", $forms['type_name'],  $forms['id'] );
			}
			if ( $dao->exits($where) ) {
				$err->clear = false;
				$err_mes['type_name'] = '<p class="error">この種類は重複しています</p>';
			}
		}
		
		if( $err->clear ){
			foreach ($types as  $k =>$v){
				$subvalues[$k] = $forms["type{$k}"] ;
			}
			

			try {
				$executeflg = TRUE;
				if( $forms['id'] == '' ){
					if ($id = $dao->add($values)) {
						$forms['id'] =  $id;
					} else {
						$executeflg = false; 
					}
				}else{
					if ($dao->edit( $forms['id'], $values )) {
						
					} else {
						$executeflg = false; 
					}
					$id = $forms['id'];
				}
				
				
				if  ($executeflg) {
					
					$msg =  '更新が完了しました。';
				} else {
					$msg =  '更新が失敗しました。';
				}
					
				
			} catch (Exception $e) {
				$msg = 'ＤＢエラーで失敗しました。';
			}
			$smarty->assign('message', $msg);
			$phase = 'complete';
		}else{
			$phase = 'input';
		}
	}
}

if( isset( $forms ) ) $smarty->assign('forms', $forms);
if( isset( $err_mes ) ) $smarty->assign('err', $err_mes);

if ($phase != 'complete') {
	
}

$smarty->assign('tmtypes', $types );
$smarty->assign('phase', $phase );
$smarty->assign('menu', $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );

$smarty->display('mcost_dm_price_type_form.html');
?>